/**
 * 组织选择树形弹框
 */
import React from 'react';
import requests from '@/utils/request';
import { Input, Modal, Tree } from 'antd';
import './style.less';
import { asserts } from '@/utils';
import { ElNotification } from '@/components/el';

interface Props {
  value?: any;
  placeholder: string;
  disabled: boolean;
  showColumn: string;
  onChange?: Function;
}
interface State {
  isTreeModal: boolean;
  treeData: Array<any>;
  selectedNodes: any;
  value: any;
}
const getInputValue = (record, showColumn) => {
  if (!record) {
    return '';
  }
  return Array.isArray(record)
    ? record.map((v) => v[showColumn]).toString()
    : record[showColumn];
};
// 在此处组装所有的数据
class OrgTreePopupSelection extends React.Component<Props, State> {
  constructor(props) {
    super(props);
    this.state = {
      isTreeModal: false,
      treeData: [],
      selectedNodes: null,
      value: null
    };
  }

  async componentDidMount() {
    // 现不提供通过code找到对应id的方法，只能先用分页查询的接口去寻找code对应的id
    // 在系统设置里面拿编号去查code，然后在组织树里面拿code去查id
    let code = '';
    const codeResponse = await requests(`/yst-system/sys/settings/q`, {
      method: 'POST',
      query: {
        current: 1,
        settingNo: 'BUSI_TREE_CODE',
        size: 20
      }
    });
    // 获取系统设置里面的code
    if (codeResponse && codeResponse.success) {
      code = codeResponse?.data?.records[0]?.settingVal;
    } else {
      return ElNotification({
        type: 'error',
        message: codeResponse.msg || '获取组织树编码失败'
      });
    }
    let id = '';
    //通过上面获取到的code去寻找组织树列表里面的id
    let response = await requests(`/yst-support/org/component/orgBuTree/list`, {
      method: 'POST',
      query: {
        buTreeCode: code,
        size: 10,
        current: 1,
        orders: [{ asc: false, column: 'createTime' }]
      }
    });
    if (response && response.success && response?.data?.records[0]) {
      id = response?.data?.records[0]?.id;
    } else {
      return ElNotification({
        type: 'error',
        message: response.msg || '获取组织树id失败'
      });
    }
    let res: any = {};
    let newTreeData = [];
    //通过拿到的id去获取对应的组织树的数据
    if (asserts.isExist(id)) {
      res = await requests(`/yst-support/org/orgBuTree/getById/${id}`, {
        method: 'get'
      });
      if (res && res.success) {
        newTreeData = JSON.parse(
          JSON.stringify(res.data.orgBuTreeDVOList || [])
            .replace(/buName/g, 'title')
            .replace(/id/g, 'key')
            .replace(/treeNodes/g, 'children')
        );
      }
    }

    this.setState({
      treeData: newTreeData
    });
  }

  /**
   * 点击查询按钮控制弹框显隐
   */
  handleSearch = () => {
    this.setState({ isTreeModal: true });
  };
  /**
   * 取消
   */
  onCancel = () => {
    this.setState({ isTreeModal: false });
  };

  /**
   *  选中树节点
   * @param selectedKeys
   * @param e
   */
  onSelectNode = (
    selectedKeys,
    e: { selected: boolean; selectedNodes: any; node: any; event: any }
  ) => {
    let selectedNodes = [];
    if (selectedKeys.length) {
      selectedNodes = e.selectedNodes;
    }
    this.setState({ selectedNodes });
  };

  /**
   * change事件
   */
  handleChange = () => {
    console.log(123);
  };

  /**
   * 点击弹框确定
   * @returns
   */
  onOk = () => {
    const { selectedNodes } = this.state;
    if (!selectedNodes) {
      this.setState({
        isTreeModal: false
      });
      return;
    }
    const buObj = {
      buId: selectedNodes.length > 0 ? selectedNodes[0].buId : '',
      buTreeDId: selectedNodes.length > 0 ? selectedNodes[0].key : '',
      buTreeId: selectedNodes.length > 0 ? selectedNodes[0].buTreeId : '',
      buName: selectedNodes.length > 0 ? selectedNodes[0].title : '',
      buCode: selectedNodes.length > 0 ? selectedNodes[0].buCode : ''
    };
    const inputValue = getInputValue(
      [buObj],
      this.props.showColumn || 'buName'
    );
    this.setState(
      {
        value: inputValue,
        isTreeModal: false
      },
      () => {
        if (this.props.onChange) {
          this.props.onChange(buObj);
        }
      }
    );
  };

  render() {
    const { isTreeModal, treeData, value } = this.state;

    return (
      <div className='orgTreeStyle'>
        <Input.Search
          readOnly
          disabled={this.props.disabled}
          placeholder={this.props.placeholder}
          value={value}
          allowClear
          onChange={this.handleChange}
          onSearch={this.handleSearch}
        />
        {isTreeModal && (
          <Modal
            title='选择组织'
            visible={isTreeModal}
            width={600}
            onOk={this.onOk}
            zIndex={100000}
            onCancel={this.onCancel}
          >
            <Tree
              height={500}
              onSelect={this.onSelectNode}
              defaultExpandAll
              treeData={treeData}
            />
          </Modal>
        )}
      </div>
    );
  }
}
export default OrgTreePopupSelection;
